#! /usr/bin/awk -f
# $OpenBSD: $
#
# Copyright (c) 2003 Henric Jungheim
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. The name of the author may not be used to endorse or promote products
#    derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

function generate_code(text, lines, key2, value2) {
	for(r in row) {
		print "/*"
		print " * Implementing", value[r,"<TYPE>"]
		print " */"
		print
		for(i = 1; i <= lines; ++i) {
			out = text[i];
			for(k in key)
				gsub(key[k], value[r,key[k]], out);
			for(k in key2)
				gsub(key2[k], value2[key2[k]], out);

			print out;
		}
	}
}

BEGIN {
	lines = 1;
	raw_lines = 1;
	split("<NUM> <TYPE> <FMT> <LOAD> <STORE>", key);
	n = split( \
		"1,u_int8_t,%2.2x,lduba,stba;" \
		"2,u_int16_t,%4.4x,lduha,stha;" \
		"4,u_int32_t,%8.8x,lduwa,stwa;" \
		"8,u_int64_t,%16.16llx,ldxa,stxa", row, ";");
	for(r in row) {
		if(split(row[r], tmp, ",") != length(key)) {
			print "bad column at ", r;
			print "row =", row[r];
			exit;
		}
		for(k in key)
			value[r,key[k]] = tmp[k]; 
		delete tmp;
	}
	print "/*"
	print " * THIS FILE IS AUTOMATICALLY GENERATED.  DO NOT EDIT."
	print " */"
	print
}

match($0, "^ECHO:") {
	print substr($0, RLENGTH + 1);
	next;
}

match($0, "^NRAW:") {
	text[lines] = substr($0, RLENGTH + 1);
	lines++;
	next;
}

match($0, "^RAW:") {
	raw_text[raw_lines] = substr($0, RLENGTH + 1);
	raw_lines++;
	next;
}

{
	text[lines] = $0;
	lines++;
	raw_text[raw_lines] = $0;
	raw_lines++;
}

END {
	k2[1] = "<RAW>"; k2[2] = "<ASI>";
	v2[k2[1]] = "";
	v2[k2[2]] = "asi";
	generate_code(text, lines, k2, v2);
	v2[k2[1]] = "raw_";
	v2[k2[2]] = "sasi";
	generate_code(raw_text, raw_lines, k2, v2);
}

